<template>
  <el-dialog v-model="dialogData.visible"
      :title="dialogData.isUpdate ? '编辑角色' : '新增角色'" width="30%" @close="closeDialog">
    <el-form ref="roleForm" :model="dialogData.role" :rules="roleRules" label-width="80">
      <el-form-item label="角色编号" v-show="dialogData.isUpdate">
        <el-input v-model="dialogData.role.id" readonly/>
      </el-form-item>
      <el-form-item label="角色名称" prop="name">
        <el-input v-model="dialogData.role.name" placeholder="请输入角色名称" clearable/>
      </el-form-item>
      <el-form-item label="英文名称" prop="enName">
        <el-input v-model="dialogData.role.enName" placeholder="请输入英文名称" clearable/>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="saveRole(roleForm)">
          保存
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import {defineProps, ref} from 'vue'
import {FormInstance} from "element-plus";
import {doPost, doPut} from '../../components/ajax'
import { showAlert } from '../../components/tip'

  const checkEnName = (rule: any, value: any, callback: any) => {
    if(/[A-Z_]+/.test(value)){
      callback()
    } else {
      callback(new Error("角色英文名称只能由大写字母和下划线组成"))
    }
  }

  const roleRules = {
    name: [
      {required: true, message: '请输入角色名称', trigger: 'blur'}
    ],
    enName: [
      {required: true, message: '请输入英文名称', trigger: 'blur'},
      {validator: checkEnName, trigger: 'blur'}
    ]
  }

  const roleForm = ref<FormInstance>()

  //定义调用组件要传递的参数
  const props = defineProps({
    dialogData: Object
  })

  //定义调用组件要传递的函数
  const emit = defineEmits(['searchEvent'])

  const closeDialog = () =>{
    roleForm.value.resetFields()
    props.dialogData.role = {}
    props.dialogData.visible = false
  }

  const saveRole = (form: FormInstance | undefined) => {
    if(!form) return;
    form.validate(valid => {
      if(valid){
        //做提交
        if(props.dialogData.isUpdate){
          doPut("/role", props.dialogData.role, resp=>{
            if(resp.data){
              showAlert("提示", "修改成功", () =>{
                closeDialog()
                //调用一次查询
                emit('searchEvent')
              })
            } else {
              showAlert("提示", "修改失败", null)
            }
          })
        } else {
          doPost("/role", props.dialogData.role, resp=>{
            if(resp.data){
              showAlert("提示", "新增成功", () =>{
                closeDialog()
                //调用一次查询
                emit('searchEvent')
              })
            } else {
              showAlert("提示", "新增失败", null)
            }
          })
        }
      } else {
        return false;
      }
    })
  }
</script>

<style scoped>

</style>
